const Router = require("koa-router");
const db = require("../database");
const router = new Router({
    prefix: "/params"
});
router.get("/getVal", async function (ctx) {
    console.log(ctx.query);
    ctx.body = {
        msg: "获取参数成功",
        query: ctx.query
    };
});
router.get("/header", async function (ctx) {
    console.log("======================");
    // console.log(ctx.headers);
    console.log(ctx.headers['x-requested-with']);
    ctx.body = {
        msg: "请求头获取参数成功",

    };
});


// 如果发送的请求是路径参数，服务器端参数如果不定义，koa-router不会加载该路径，认为访问的路径地址不存在
// koa-router为ctx提供一个特殊的参数数据，ctx.params,该参数是专门用于路径参数的获取
router.get("/getUser/:id", async function (ctx) {
    let users = [
        { name: "tom" },
        { name: "alice" },
        { name: "lucy" },
        { name: "cici" }

    ];
    let i = ctx.params.id;
    if (i >= users.length) {
        ctx.body = {};
    } else {
        ctx.body = users[i];
    }

});

router.post("/body", async function (ctx) {
    console.log(ctx.request.body);
    console.log(ctx.request.files);
    ctx.body = {
        msg: "获取请求体参数成功"
    };
});

router.get("/result", async function (ctx) {
    console.log("=======================");
    let html = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
        </head>
        <body>
            <h2>我是页面呀</h2>
        </body>
        </html>
    `;

    // ctx.type="html";//koa设置响应的类型，响应头中Content-type

    ctx.cookies.set("aa","123456");
    ctx.cookies.set("token","12345678");
    let a="aaa";
    ctx.body = a;
});
router.get("/text", async function (ctx) {
    ctx.type="text";
    ctx.body="蔡徐坤,朱一龙,王一博,孙志远,于峰";
});
router.get("/html", async function (ctx) {
    ctx.type="html";
    ctx.body=`
        <li>胡歌</li>
        <li>靳东</li>
        <li>王凯</li>
        <li>易烊千玺</li>
        <li>王俊凯</li>
    
    `;
});

router.get("/arr", async function (ctx) {
    ctx.type="json";
    ctx.body=["蔡徐坤","朱一龙","王一博","孙志远","于峰"];
});
module.exports.paramsRouter = router;